import React, { useEffect, useRef } from 'react'
import L from 'leaflet'
import 'leaflet/dist/leaflet.css'
import type { PointData, MergedPoint, SelectedPoint, TimeRange } from '../types'

interface MapContainerProps {
  pointsData: PointData[];
  selectedTimeRange: TimeRange | null;
  selectedPoints: SelectedPoint[];
  onPointSelect: (selectedPoint: SelectedPoint) => void;
  mergeOverlappingPoints: (points: PointData[], threshold?: number) => MergedPoint[];
  createCustomIcon: (count: number, isSelected?: boolean, mergedPoint?: MergedPoint) => L.DivIcon;
  createPopupContent: (mergedPoint: MergedPoint) => string;
  focusPoint?: { latitude: number; longitude: number };
}

const MapContainer: React.FC<MapContainerProps> = ({
  pointsData,
  selectedTimeRange,
  selectedPoints,
  onPointSelect,
  mergeOverlappingPoints,
  createCustomIcon,
  createPopupContent,
  focusPoint
}) => {
  const mapRef = useRef<HTMLDivElement>(null)
  const mapInstanceRef = useRef<L.Map | null>(null)
  const markersRef = useRef<L.Marker[]>([])

  useEffect(() => {
    if (mapRef.current && !mapInstanceRef.current) {
      // 修复leaflet默认图标问题
      delete (L.Icon.Default.prototype as any)._getIconUrl
      L.Icon.Default.mergeOptions({
        iconRetinaUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/images/marker-icon-2x.png',
        iconUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/images/marker-icon.png',
        shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/images/marker-shadow.png'
      })

      // 创建地图实例
      const map = L.map(mapRef.current).setView([27.07, 116.12], 11)

      // 添加多个地图图层选项
      const baseMaps = {
        // 高德地图 - 通常在中国大陆访问较稳定
        "高德地图": L.tileLayer('https://webrd02.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}', {
          attribution: '© 高德地图'
        }),
        
        // 高德卫星图 - 显示真实地形地貌
        "高德卫星图": L.tileLayer('https://webst02.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}', {
          attribution: '© 高德地图卫星图'
        }),
        
        // 天地图 - 中国官方地图服务
        "天地图": L.tileLayer('https://t0.tianditu.gov.cn/vec_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=替换为你的天地图key', {
          attribution: '© 天地图'
        }),
        
        // 天地图地形图 - 显示地形等高线
        "天地图地形": L.tileLayer('https://t0.tianditu.gov.cn/ter_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=ter&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=替换为你的天地图key', {
          attribution: '© 天地图地形'
        }),
        
        // OpenStreetMap - 备用选项
        "OpenStreetMap": L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
          attribution: '© OpenStreetMap contributors'
        }),
        
        // 地形阴影图 - 显示立体地形效果
        "地形阴影图": L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Shaded_Relief/MapServer/tile/{z}/{y}/{x}', {
          attribution: '© Esri'
        }),
        
        // 地形等高线图 - 详细的地形信息
        "地形等高线": L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/tile/{z}/{y}/{x}', {
          attribution: '© Esri'
        }),
        
        // 卫星图像 - 真实地形地貌
        "卫星图像": L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
          attribution: '© Esri WorldImagery'
        }),
        
        // 混合地形图 - 卫星图像+地名标注
        "混合地形": L.tileLayer('https://mt1.google.com/vt/lyrs=y&x={x}&y={y}&z={z}', {
          attribution: '© Google'
        }),
        
        // 物理地形图 - 显示地形起伏
        "物理地形": L.tileLayer('https://mt1.google.com/vt/lyrs=p&x={x}&y={y}&z={z}', {
          attribution: '© Google'
        }),
        
        // CartoDB - 另一个稳定的选项
        "CartoDB": L.tileLayer('https://{s}.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}{r}.png', {
          attribution: '© CartoDB'
        }),
        
        // Stamen Terrain - 地形图
        "Stamen地形": L.tileLayer('https://stamen-tiles-{s}.a.ssl.fastly.net/terrain/{z}/{x}/{y}{r}.png', {
          attribution: '© Stamen Design'
        })
      }

      // 默认使用地形阴影图来显示立体效果，如果失败则可以手动切换
      baseMaps["地形阴影图"].addTo(map)

      // 添加图层控制器，用户可以切换不同的地图源
      L.control.layers(baseMaps).addTo(map)

      // 合并重合点
      const mergedPoints = mergeOverlappingPoints(pointsData)
      
      // 添加所有标记点
      const markers: L.Marker[] = []
      mergedPoints.forEach((mergedPoint, index) => {
        const icon = createCustomIcon(mergedPoint.count, false, mergedPoint)
        const popupContent = createPopupContent(mergedPoint)
        
        const marker = L.marker([mergedPoint.latitude, mergedPoint.longitude], { icon })
          .addTo(map)
          .bindPopup(popupContent, {
            maxWidth: 300,
            className: 'custom-popup'
          })
        
        markers.push(marker)
        
        // 添加鼠标悬浮效果
        marker.on('mouseover', function(this: L.Marker) {
          this.openPopup()
        })
        
        // 添加点击选择功能
        marker.on('click', function(this: L.Marker) {
          const selectedPoint = { point: mergedPoint, marker, index }
          onPointSelect(selectedPoint)
        })
      })
      
      markersRef.current = markers

      // 添加地图加载错误处理
      map.on('tileerror', (e) => {
        console.warn('地图瓦片加载失败:', e)
      })

      // 添加地图加载成功提示
      map.on('tileload', () => {
        console.log('地图瓦片加载成功')
      })

      mapInstanceRef.current = map
    }

    // 清理函数
    return () => {
      if (mapInstanceRef.current) {
        mapInstanceRef.current.remove()
        mapInstanceRef.current = null
      }
    }
  }, [pointsData])

  // 监听时间范围变化，更新标记点颜色
  useEffect(() => {
    if (!selectedTimeRange) return
    
    const mergedPoints = mergeOverlappingPoints(pointsData)
    markersRef.current.forEach((marker, index) => {
      const mergedPoint = mergedPoints[index]
      if (mergedPoint) {
        const isSelected = selectedPoints.some(sp => sp.index === index)
        const newIcon = createCustomIcon(mergedPoint.count, isSelected, mergedPoint)
        marker.setIcon(newIcon)
        
        // 更新弹窗内容
        const popupContent = createPopupContent(mergedPoint)
        marker.bindPopup(popupContent, {
          maxWidth: 300,
          className: 'custom-popup'
        })
      }
    })
  }, [selectedTimeRange, selectedPoints, pointsData])

  // 监听焦点点变化，移动地图视角
  useEffect(() => {
    if (focusPoint && mapInstanceRef.current) {
      mapInstanceRef.current.setView([focusPoint.latitude, focusPoint.longitude], 15, {
        animate: true,
        duration: 1
      })
    }
  }, [focusPoint])

  return (
    <div 
      ref={mapRef} 
      style={{ 
        width: '100%', 
        flex: 1,
        border: 'none'
      }}
    />
  )
}

export default MapContainer 